package eraas
{
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	public class EraSocket
	{
		private var socketServer:Socket; 
		
		public function EraSocket()
		{
			
			//连接服务器
			var server:String="localhost";
			var port:int=9999;
			
			socketServer=new Socket(server, port);
			//配置事件监听器
			configListeners();
		}
		
		/**
		 * 配置事件监听器
		 */
		private function configListeners():void
		{
			//socket关闭事件
			socketServer.addEventListener(Event.CLOSE, closeHandler);
			//socket连接成功事件
			socketServer.addEventListener(Event.CONNECT, connectHandler);
			//socket连接不成功出的IO错误事件
			socketServer.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			//访问权限出错事件
			socketServer.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			//
			socketServer.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
			
		}
		
		//socket写字节函数
		private function writeln(str:String):void
		{
			str+="\n";
			try
			{
				socketServer.writeUTFBytes(str);
			}
			catch (e:IOError)
			{
				trace(e);
			}
		}
		
		//发送信息函数
		private function sendRequest(str:String):void
		{
			//trace("sendRequest");
			//response+=inTxt.text + "\n";
			writeln(str);
			socketServer.flush();
			//inTxt.text = "";
		}
		
		//读入响应信息函数
		private function readResponse():String
		{
			var str:String=socketServer.readUTFBytes(socketServer.bytesAvailable);
			return str;
		}
		
		/**
		 * 关闭处理函数
		 */
		private function closeHandler(event:Event):void
		{
			trace("closeHandler: " + event);
			//trace(response.toString());
		}
		
		/**
		 * 连接成功处理函数
		 */
		private function connectHandler(event:Event):void
		{
			trace("connectHandler: " + event);
			//response+="已连接"
		}
		
		/**
		 * socket的IO错误处理函数
		 */
		private function ioErrorHandler(event:IOErrorEvent):void
		{
			trace("ioErrorHandler: " + event);
		}
		
		/**
		 * 安全错误处理函数
		 */
		private function securityErrorHandler(event:SecurityErrorEvent):void
		{
			trace("securityErrorHandler: " + event);
		}
		
		/**
		 * socket处理函数
		 */
		private function socketDataHandler(event:ProgressEvent):void
		{
			trace("socketDataHandler: " + event);
			readResponse();
		}
		
		/**
		 * 发送按钮点击事件处理函数
		 */
		private function onClick(evt:Event):void
		{
			//sendRequest();
		}
	}
}